# -*- coding: utf-8 -*-
import logging
from info import phone


# 自定义异常
class DataException(Exception):
    def __init__(self, error):
        self.error = error

    def __str__(self, *args, **kwargs):
        return self.error


def clean_data(data_type, data_content):
    """

    :param data_type:性能类型
    :param data_content:完整的性能数据
    :return: 过滤后的数据
    """
    if data_content is not None:
        try:
            if data_type == 'cpu':
                content_list = str(data_content).split(" ")
                cpu_list = [i for i in content_list if i != '']
                return round(float(cpu_list[20]) / int(phone.get_cpu_kel()), 2)

            if data_type == 'memory':
                for line in str(data_content).split("\\n"):
                    cur_line = line.strip().split(" ")
                    if cur_line[0] == "TOTAL":
                        total = [x for x in cur_line if x]
                        total = round(float(int(total[1]) / float(1024)), 2)
                        return total

            if data_type == 'battery':
                level_bat = str(data_content).split('\\n')[11].split(':')[1]
                return level_bat

            if data_type == 'flow':
                flow_list = str(data_content).split(' ')
                flow_list = [x for x in flow_list if x]
                receive_flow = round(float(flow_list[2]) / 1024, 2)
                transmit_flow = round(float(flow_list[10]) / 1024, 2)
                flow = receive_flow + transmit_flow
                return flow

            if data_type == 'temperature':
                # 单位是0.1摄氏度
                data_content = str(data_content).split(':')[1].split('\\n')[0]
                return float(data_content) / 10

        except IndexError:
            return 0
        except ValueError:
            return 0

    else:
        logging.warning("Error! ")
